package cn.bx.bid.ctrl;

import cn.bx.bid.entity.AjaxResult;
import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UserAjaxController {

    @Autowired
    private UserService userService;

    @RequestMapping("search")
    @ResponseBody
    public Page<User> search(@RequestParam(name = "pageNo",defaultValue = "1")int pageNO, @RequestParam(name = "name",required = false)String name,
                             @RequestParam(name = "startDate",required = false) Date start, @RequestParam(name = "endDate",required = false)Date end ) {
        Page<User> page = userService.paging(pageNO,Page.PAGE_SIZE,name,start,end);
        return page;
    }

    @GetMapping("delUser")
    @ResponseBody
    public AjaxResult del(@RequestParam("uid") int id){
        long[] ids = {id};
        int flag = userService.batchDel(ids);
        return flag>0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @RequestMapping("getUser")
    @ResponseBody
    public User get(@RequestParam("uid") int id){
        return userService.get(id);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }
    }
}
